# -- coding:UTF-8 --

import os
import sys
import json
import time
import datetime

# cocos路径
# CCCPath = 'E:/CocosDashboard/resources/.editors/Creator/2.3.3/'
# CreatorPath = CCCPath + 'CocosCreator.exe'
CreatorPath =  'CocosCreator.exe'
# 项目地址
Path_Project=sys.path[0]
Path_Project=Path_Project.replace('\commands' , '')
# 跳过astc压缩文件
jumpFiles = ["sjzx_bg_01", "button_gold1", "icon_center_6508", "icon_center_287", "icon_center_6500", "icon_center_6903", "zjm_sirenyingyuan", 
"603_Suit_m_0", "686_Suit_m_0", "578_Suit_m_0", "2466_Suit_baremold_m_0", "2466_Suit_baremold_m_02",
 "2449_Suit_baremold_m_0", "2585_Suit_baremold_m_0", "5182_Suit_baremold_m_0", "2603_Suit_baremold_m_0", "mengxinying", "style_bg_1"]
# 4*4 astc压缩文件
# astc44 = ["603_Suit_m_0", "686_Suit_m_0", "578_Suit_m_0", "2466_Suit_baremold_m_0", "2466_Suit_baremold_m_02",
#  "2449_Suit_baremold_m_0", "2585_Suit_baremold_m_0", "5182_Suit_baremold_m_0", "2603_Suit_baremold_m_0", "mengxinying", "style_bg_1"]


def getNowDate():
    now = datetime.datetime.now()
    # 转换为指定的格式:
    nowTime = now.strftime("%Y%m%d")
    return nowTime

# 获得当前时间
def getNowTime():
    now = datetime.datetime.now()
    # 转换为指定的格式:
    nowTime = now.strftime("%Y-%m-%d %H:%M:%S")
    return nowTime

def printNow(str):
    print(getNowTime() + " " + str)
    sys.stdout.flush()

# 跳过纹理压缩
def jumpAstc(filePath):
    for item in jumpFiles:
        if item in filePath:
            return True
    return False

# 需要4*4压缩
def isAstc44(filePath):
    for item in astc44:
        if item in filePath:
            return True
    return False

def changeMeta(filePath, pvrType):
    printNow(filePath)
    with open(filePath, "r",encoding="utf-8") as load_f_r:
        load_f_r = json.load(load_f_r)

    if "platformSettings" in load_f_r:
        load_f_r["platformSettings"] = {"wechatgame": {
            "formats": [{"name": pvrType, "quality": "normal"}, { "name": "png", "quality": 99 }]}}
        with open(filePath, "w") as dump_f:
            json.dump(load_f_r, dump_f, indent=2)
    else:
        printNow("empty platformSettings:" + filePath)

# 批量修改meta，待进一步完善
def getAllImageMeta(folderPath, extend_name):
    for item in os.listdir(folderPath):
        if os.path.isdir(os.path.join(folderPath, item)):
            subFolderPath = os.path.join(folderPath, item)
            getAllImageMeta(subFolderPath, extend_name)
        else:
            filePath = os.path.join(folderPath, item)
            if (os.path.isfile(filePath)) and ("commonUIRes" in filePath):
                return 0
            if jumpAstc(filePath):
                return 0

            if (os.path.isfile(filePath)) and (item.split('.')[-1] == "meta"):
                if ("_Face_m_" in filePath):
                    if item.split('.')[-2] in extend_name:
                        changeMeta(filePath, "pvrtc_4bits")
                # elif isAstc44(filePath):
                #     if item.split('.')[-2] in extend_name:
                #         changeMeta(filePath, "pvrtc_4bits")
                else:
                    if item.split('.')[-2] in extend_name:
                        changeMeta(filePath, "pvrtc_2bits")
                    
    return 0

def setMeta(path, extend_name):
    if os.path.exists(path):
        getAllImageMeta(path, extend_name)


def checkASTC(filePath):
    printNow(filePath)
    with open(filePath,"r", encoding="utf-8") as load_f:
        load_f = json.load(load_f)
    # print(load_f)
    # dict类型
    if isinstance(load_f, dict):
        if "__type__" in load_f:
            if load_f["__type__"] == "cc.Texture2D":
                load_f["content"] = load_f["content"].replace("5@8", "7@30").replace("5@6", "7@37")

        if "type" in load_f:
            if load_f["type"] == "cc.Texture2D":
                load_f["data"] = load_f["data"].replace("5@8", "7@30").replace("5@6", "7@37")

    # list类型
    if isinstance(load_f, list):
        for value in load_f:
            if "__type__" in value:
                if value["__type__"] == "cc.Texture2D":
                    value["content"] = value["content"].replace("5@8", "7@30").replace("5@6", "7@37")

            if "type" in value:
                if value["type"] == "cc.Texture2D":
                    value["data"] = value["data"].replace("5@8", "7@30").replace("5@6", "7@37")

    with open(filePath, "w", encoding="utf-8") as dump_f:
        json.dump(load_f, dump_f, indent=2)


def getAllImageAstc(folderPath, extend_name):
    for item in os.listdir(folderPath):
        if os.path.isdir(os.path.join(folderPath, item)):
            subFolderPath = os.path.join(folderPath, item)
            getAllImageAstc(subFolderPath, extend_name)
        else:
            filePath = os.path.join(folderPath, item)
            if os.path.isfile(filePath):
                if item.split('.')[-1] in extend_name:
                    checkASTC(filePath)
    return 0


def setASTC(path, extend_name):
    if os.path.exists(path):
        getAllImageAstc(path, extend_name)


# 上传cdn
def uploadCDN(remoteDirName):
    printNow("Start uploadCDN")
    os.chdir(Path_Project)
    os.system("coscmd config -a AKIDLafy4v97WkjaM4t4PXklYEl9SiljE9cr -s GaHn3RPZXM5ZwX5sTtRnyyjJjNAnBSUG -b game-zj-cdn-1251697691 -r ap-shanghai -m 30 --do-not-use-ssl")
    cmd = "coscmd upload -r " + Path_Project + "\\build\\res"
    os.system(cmd + " qjwx_test\\" + remoteDirName + "\\res")
    printNow("End uploadCDN")


#---------------------------------main----------------------------#
printNow("start change all [png.meta, pac.meta, jpg.meta]...\n")
# setMeta("..\\assets", ["png", "jpg", "pac"])
setMeta("..\\assets", ["png", "jpg"])
printNow("setMeta finish")

printNow("start buildPoject:")
buildCommand = '--build debug=false;platform=wechatgame'
os.system(CreatorPath + " --path ../ " + buildCommand)
printNow("buildPoject finish.")

printNow(Path_Project + "\\build\\wechatgame\\res\\import")
printNow("start change all [png.meta, pac.meta]...\n")
setASTC(Path_Project + "\\build\\wechatgame\\res\\import", ["json"])
setASTC(Path_Project + "\\build\\wechatgame\\res_internal\\import", ["json"])
printNow("setASTC finish.")

# printNow(Path_Project)
# os.system(Path_Project + "\\build\\wechatgame\\autorun.sh")
# remoteDirName = getNowDate()
# printNow(remoteDirName)
# uploadCDN(remoteDirName)

printNow("done...\n")
# os.system('pause')
 